﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RMS.Common
{
    public class EntityHelper
    {
        /// <summary>
        /// 实体对象相互转换   有相同属性的值可以互相获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T ConverToTEntity<T>(object value)
        {
            Type t = typeof(T);
            System.Reflection.PropertyInfo[] t_propinfos = t.GetProperties();
            T obj = (T)t.Assembly.CreateInstance(t.FullName);
            if (value != null)
            {
                Type val_t = value.GetType();

                System.Reflection.PropertyInfo[] val_t_propinfos = val_t.GetProperties();

                foreach (System.Reflection.PropertyInfo vp in val_t_propinfos)
                {
                    System.Reflection.PropertyInfo tp = t_propinfos.FirstOrDefault(m => m.Name == vp.Name);
                    if (tp != null)
                    {
                        object val = vp.GetValue(value);
                        tp.SetValue(obj, val, null);
                    }
                }
            }
            return obj;
        }
        /// <summary>
        /// 实体对象列表相互转换   有相同属性的值可以互相获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static List<T> ConverToTEntityList<T, M>(List<M> value)
        {
            List<T> list = new List<T>();
            foreach (M obj in value)
            {
                T t = ConverToTEntity<T>(obj);
                list.Add(t);
            }
            return list;
        }
    }
}
